import http from "axios";
import qs from "qs";
import { getToken,setHisLastUrl, WeiXinEnv, AlipayEnv, QQEnv } from "./cookie";

// axios 封装及配置
//  http.defaults.baseURL = 'https://api.example.com';
//  http.defaults.headers.common['Authorization'] = AUTH_TOKEN;
//  http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


// http.defaults.baseURL = process.env.VUE_APP_URL;
// http.defaults.baseURL = '';
// http.defaults.httpImgUrl = process.env.VUE_APP_IMG_ROOT;


http.defaults.timeout = 5000;
http.defaults.headers.post['Content-Type'] = 'application/json'
// http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// cache-control: "max-age=0, private, must-revalidate"
// http.defaults.headers.post['Cache-control'] = 'max-age=5'

// 重试次数
http.defaults.retry = 2;

// 重试延时
http.defaults.retryDelay = 5000;

// 重试条件，默认只要是错误都需要重试
http.defaults.shouldRetry = (error) => true;

// 检测token是否存在
http.defaults.hasToken = getToken();

// http request 拦截器
http.interceptors.request.use(function (config) {
    let url = config.url;

    //判断是否存在token，如果存在将每个页面header都添加token
    if (config.method === "post" || config.method === "get" || config.method == "put") {
        if ( getToken() && getToken() != '' && getToken() != '""' && getToken().length > 0 ) {
            config.headers['Token'] = getToken();
            http.defaults.hasToken = getToken();
        }
    }

    // Do something before request is send
    if (config.method === 'get') {
        // 防止请求get时候，部分符号不转义 如[]
        if(config.params) {
            url += '?';
            let keys = Object.keys(config.params);
            for (let key of keys) {
                url += `${key}=${encodeURIComponent(config.params[key])}&`
            }
            url = url.substring(0, url.length - 1);
            config.params = {}
        }
        else {
            url = encodeURI(config.url);
        }
        config.url = url;
    }

    if (config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }

    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error)
})

// Add a response interceptor
// http response 拦截器
http.interceptors.response.use(function (response) {
    // Do something with response data
    let _data = response.data.data;
    let _ret = response.data.ret;
    setHisLastUrl(window.location.href);
    // if (_ret.code == '00100') {
    //     // 微信 支付宝 QQ默认登录  WeiXinEnv, AlipayEnv, QQEnv
    //     if( WeiXinEnv() || AlipayEnv() || QQEnv() ) {
    //         // console.log('第三方环境')
    //         window.location.href = process.env.VUE_APP_URL + 'm/u/publicly/auth/1.0/login';
    //     }
    //     else {
    //         // 正常页面跳转登录
    //         // console.log('正常页面跳转登录')
    //         window.location.href = process.env.VUE_APP_URL + 'h/login/loginMobile';
    //     }
    // }
    return response;

}, function (err) {
    // Do something with response error
    if (err.response) {
        switch (err.response.status) {
            case 302:
                err.message = '重定向';
                break;
            case 400:
                err.message = '请求错误';
                break;
            case 401:
                err.message = '未授权，请登录';
                break;
            case 403:
                err.message = '拒绝访问';
                break;
            case 404:
                err.message = '请求地址出错';
                break;
            case 408:
                err.message = '请求超时';
                break;
            case 429:
                window.location.href= process.env.VUE_APP_IMG_ROOT+'errorPage/429.html';
                break;
            case 500:
                err.message = '服务器内部错误';
                break;
            case 501:
                err.message = '服务未实现';
                break;
            case 502:
                err.message = '网关错误';
                break;
            case 503:
                err.message = '服务不可用';
                break;
            case 504:
                // err.message = '网关超时';
                window.location.href= '/h/login/serve504';
                break;
            case 505:
                err.message = 'HTTP版本不受支持';
                break;
            default:
                break;
        }
    }
    else if (err.code == "ECONNABORTED") {
        err.message = '服务器请求超时，请稍后重试';
    }
    // return Promise.reject(error)

    let config = err.config;
    // 判断是否配置了重试

    if(!config || !config.retry) return Promise.reject(err);

    if(!config.shouldRetry || typeof config.shouldRetry != 'function') {
        return Promise.reject(err);
    }

    //判断是否满足重试条件
    if(!config.shouldRetry(err)) {
        return Promise.reject(err);
    }

    // 设置重置次数，默认为0
    config.__retryCount = config.__retryCount || 0;

    // 判断是否超过了重试次数
    if(config.__retryCount >= config.retry) {
        return Promise.reject(err);
    }

    //重试次数自增
    config.__retryCount += 1;

    //延时处理
    let backoff = new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, config.retryDelay || 1);
    });

    // 重新发起请求
    return backoff.then(function() {
        // 处理重新请求时 post方法里的数据格式成字符串，这里处理成json格式
        if(config.method == 'post' && config.data) {
            let newData = {};
            let _datajson = [];
            if(config.data.indexOf('&') > 0)  {
                let _dataArr = config.data.split('&');
                for(let i=0; i<_dataArr.length; i++) {
                    _datajson = _dataArr[i].split('=');
                    newData[ _datajson[0] ] = _datajson[1]
                }
            }
           else {
                _datajson = config.data.split('=');
                newData[ _datajson[0] ] = _datajson[1];
           }
            config.data = newData;
        }
        return http(config);

    });
});

export default http
